package com.allsofts.pattern.course.delegate.mvc;

import com.allsofts.pattern.course.delegate.mvc.controller.MemberAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: pattern
 * @Package: com.allsofts.pattern.course.delegate
 * @description: 相当于项目经理的角色
 * @Author: liyc
 * @CreateDate: 2018/8/5 下午11:10
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
public class ServletDispatcher {

    private List<Handler> handlerMapping = new ArrayList<>();

    public ServletDispatcher() throws IllegalAccessException, InstantiationException, NoSuchMethodException {
        Class<?> memberActionClass = MemberAction.class;
        this.handlerMapping.add(new Handler().setController(memberActionClass.newInstance())
                .setMethod(memberActionClass.getMethod("getMemberById", new Class[]{String.class}))
                .setUrl("/web/getMemberById.json"));

    }

    public void doService(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException, IOException, InvocationTargetException {
        doDispatch(request, response);


    }

    private void doDispatch(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {
        //1.获取用户请求的url
        //如果按照javaee的标准，每个url对应一个servlet，url由浏览器输入
        String uri = request.getRequestURI();
        //2.servlet拿到url之后，要做权衡（要做判断，要做选择）
        //根据用户请求的url，去找的url对应的java类的方法

        //3.通过拿到的url去handlemapping（我们认为是策略常量）
        Handler handler = null;
        for (Handler h : handlerMapping) {
            if (h.getUrl().equals(uri)) {
                handler = h;
                break;
            }
        }

        //4.将具体的任务分发的method，通过反射调用具体的方法
        Object object = null;
        object = handler.getMethod().invoke(handler.getController(),request.getParameter("mid"));
        //5.获取到method的执行结果，通过Response返回出去
        response.getWriter().write((char[]) object);


    }

    class Handler {
        private Object controller;
        private Method method;
        private String url;

        public Object getController() {
            return controller;
        }

        public Handler setController(Object controller) {
            this.controller = controller;
            return this;
        }

        public Method getMethod() {
            return method;
        }

        public Handler setMethod(Method method) {
            this.method = method;

            return this;
        }

        public String getUrl() {
            return url;
        }

        public Handler setUrl(String url) {
            this.url = url;

            return this;
        }
    }

}
